package xp2p.svc;

import xp2p.utils.RandomBytes;

import net.jxta.content.ContentID;
import net.jxta.id.IDFactory;
import net.jxta.peergroup.PeerGroup;

/**
 * Basse service thread for single PeerGroup
 * 
 * @param <T>
 *            the generic type
 */
public abstract class ServiceBase implements Runnable
{
	private Object syncRoot = new Object();
	private PeerGroup group;
	protected boolean exit = false;
	
	protected boolean getExit()
	{
		synchronized(syncRoot)
		{
			if (Thread.interrupted())
			{
				exit = true;
			}
			return exit;
		}
	}
	
	protected void setExit(boolean b)
	{
		synchronized(syncRoot)
		{
			exit = b;
		}
	}

	protected ContentID CreateNewID()
	{
		return IDFactory.newContentID(getGroup().getPeerGroupID(), true,
				RandomBytes.getRandomBytes());
	}

	public PeerGroup getGroup()
	{
		synchronized (syncRoot)
		{
			return group;
		}
	}

	public void setGroup(PeerGroup group)
	{
		synchronized (syncRoot)
		{
			this.group = group;
		}
	}

	protected abstract void doRun() throws InterruptedException;

	public void run()
	{
		try
		{
			doRun();
		} catch (InterruptedException e)
		{
			synchronized (syncRoot)
			{
				exit = true;
			}
		}
	}
}
